#include <bits/stdc++.h>
using namespace std;
#define hashsize 1000003
#define maxsize 100000000
typedef int state[9];
state ns = { 0,0,0,0,0,0,0,0,0 };
state ans = { 1,2,3,8,0,4,7,6,5 };
//hash
state st[hashsize];
int head[hashsize];
int Next[hashsize];
int stend = 0;
int Hash(void) {
	int h = 0;
	for (int i = 0; i < 9; i++) {
		h *= 10;
		h += st[stend][i];
	}
	return h % hashsize;
}

bool insert(void) {
	int x = Hash();
	int h = head[x];
	while (h) {
		if (!memcmp(st[h], st[stend], sizeof(state)))
			return 0;
		h = Next[h];
	}
	Next[stend] = head[x];
	head[x] = stend;
	stend++;
	return 1;
}
//move
bool up(int* a) {
	int sign;
	for (sign = 0; a[sign]; sign++);
	if (sign < 3)return true;
	memcpy(st[stend], a, sizeof(state));
	int tmp = st[stend][sign - 3];
	st[stend][sign - 3] = 0;
	st[stend][sign] = tmp;
	return false;
}
bool down(int* a) {
	int sign;
	for (sign = 0; a[sign]; sign++);
	if (sign > 5)return true;
	memcpy(st[stend], a, sizeof(state));
	int tmp = a[sign + 3];
	st[stend][sign + 3] = 0;
	st[stend][sign] = tmp;
	return false;
}
bool left(int* a) {
	int sign;
	for (sign = 0; a[sign]; sign++);
	if (!(sign % 3))return true;
	memcpy(st[stend], a, sizeof(state));
	int tmp = st[stend][sign - 1];
	st[stend][sign - 1] = 0;
	st[stend][sign] = tmp;
	return false;
}
bool right(int* a) {
	int sign;
	for (sign = 0; a[sign]; sign++);
	if (sign % 3 == 2)return true;
	memcpy(st[stend], a, sizeof(state));
	int tmp = st[stend][sign + 1];
	st[stend][sign + 1] = 0;
	st[stend][sign] = tmp;
	return false;
}

int main(void) {
	state s, temp;
	int step = 0;
	bool (*move[4])(int*) = { up,down,left,right };
	for (int i = 0; i < 9; i++) {
		s[i] = getchar() - '0';
	}

	memset(temp, 0, sizeof(temp));
	memset(head, 0, sizeof(head));
	memset(Next, 0, sizeof(Next));
	memset(st, 0, sizeof(st));

	memcpy(st[1], s, sizeof(state));
	memcpy(st[2], ns, sizeof(state));
	stend = 1;
	insert();
	stend = 3;

	for (int i = 1; i < maxsize; i++) {

		if (!memcmp(st[i], ns, sizeof(state))) {
			memcpy(st[i], st[stend], sizeof(state));
			step++;
			stend++;
			continue;
		}
			if (!memcmp(ans, st[i], sizeof(state))) {
				cout << step;
				return 0;
			}

		for (int j = 0; j < 4; j++) {
			if ((*move[j])(st[i]))continue;


			if(!insert())memcpy(st[stend],ns,sizeof(state));

			if (stend >= maxsize) {
				cout << "Stack Overflow!i:" << i << "stend:" << stend << endl;
				return 0;
			}
		}
	}

	return 0;
}

